using Fusion.Utilities.Bit;
using System;
using System.Net.Sockets;

namespace Fusion.Net.TCP
{
    public abstract class TCPSocket : SocketBase
    {
        protected TCPNet tcp;
        protected TCPServer tcpServer;

        public TCPServer TCPServer { get => tcpServer; set => tcpServer = value; }

        protected TCPSocket(TCPNet tcp, Socket socket) : base(tcp, socket)
        {
            this.tcp = tcp;
        }

        protected TCPSocket(TCPNet tcp, AddressFamily addressFamily) : base(tcp, addressFamily, SocketType.Stream, ProtocolType.Tcp)
        {
            this.tcp = tcp;
        }

        public override void Send(byte[] data, int length)
        {
            data = Pack(data, length);
            SendPackedData(data);
        }

        public void SendPackedData(byte[] data)
        {
            try
            {
                if (socket.Connected)
                {
                    int sentLength = 0;
                    int length = data.Length;
                    while (sentLength < length)
                    {
                        sentLength += socket.Send(data, sentLength, length - sentLength, SocketFlags.None);
                    }
                }
            }
            catch (SocketException e)
            {
                HandleError(e);
            }
        }

        public override byte[] Pack(byte[] data, int length)
        {
            byte[] result = new byte[length + 5];
            result[0] = 0;
            BitUtility.WriteInt(result, 1, length);
            Array.Copy(data, 0, result, 5, length);
            return result;
        }
    }

}

